<?php
/**
 * Created by chency.
 * User: Administrator
 * Date: 2018/11/4 0004
 * Time: 下午 6:12
 */
namespace app\api\model;

use think\cache\driver\Redis;
use think\Model;

class NewsModel extends Model
{
    public $table = 'tps_news';

    private $cacheListName = 'NEWS_CACHE_LIST';

    private $cacheDetailName = 'NEWS_CACHE_DETAIL';

    /**
     * 获取列表
     * @param $map
     * @param $page
     * @param int $listRows
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList ($map, $page, $listRows = 5)
    {
        $redis = new Redis();
        $token = md5 (json_encode ([$map, $page, $listRows]));
        $list = $redis->hGet ($this->cacheListName, $token);
//        $list = [];
        if (empty($list)) {
            $list = $this
                ->field ('n.id,n.type,n.title,n.title_source,n.pic,n.url,n.description,n.created_at,n.updated_at,nt.type_name')
                ->join ('tps_news_type nt', 'nt.id = n.type', 'left')
                ->alias ('n')
                ->where ($map)
                ->order ('created_at DESC')
                ->paginate ($listRows);
            $redis->hSet ($this->cacheListName, $token, $list);
        }
        return $list;
    }

    /**
     * 获取单条
     * @param $map
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetails ($map)
    {
        $redis = new Redis();
        $token = md5 (json_encode ([$map]));
        $detail = $redis->hGet ($this->cacheDetailName, $token);
//        $detail = [];
        if (empty($detail)) {
            $detail = $this
                ->field ('n.id,n.type,n.title,n.title_source,n.pic,n.url,n.description,n.created_at,n.updated_at,n.content,nt.type_name')
                ->join ('tps_news_type nt', 'nt.id = n.type', 'left')
                ->alias ('n')
                ->where ($map)
                ->find ();
            //获取上一条 和下一条
            $detail['next_id'] = $this->where (['created_at' => ['lt', $detail['created_at']], 'type' => $detail['type']])->order ('created_at DESC')->value ('id');
            $detail['pre_id'] = $this->where (['created_at' => ['gt', $detail['created_at']], 'type' => $detail['type']])->order ('created_at DESC')->value ('id');
            $redis->hSet ($this->cacheDetailName, $token, $detail);
        }
        return $detail;
    }
}